﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Sinacor.Infra.UI.Messaging.SmartClient.WeakEventManagers
{
    internal class OnInternalMessageArrivalWeakEventArgs : EventArgs
    {
        Internal.InternalMessage _internalMessage;
        public Internal.InternalMessage InternalMessage
        {
            get { return _internalMessage; }
            set { _internalMessage = value; }
        }

        public OnInternalMessageArrivalWeakEventArgs(Internal.InternalMessage internalMessage)
        {
            _internalMessage = internalMessage;
        }
    }

    internal class OnInternalMessageArrivalManager : WeakEventManager
    {
        private object _source;
        protected override void StartListening(object source)
        {
            MessageManager c = source as MessageManager;
            if (c != null)
                c.OnInternalMessageArrival += new MessageManager.InternalMessageArrivalDelegate(OnInternalMessageArrival);

            _source = source;
        }
        protected override void StopListening(object source)
        {
            MessageManager c = source as MessageManager;
            if (c != null)
                c.OnInternalMessageArrival -= new MessageManager.InternalMessageArrivalDelegate(OnInternalMessageArrival);

            _source = null;
        }

        void OnInternalMessageArrival(Sinacor.Infra.UI.Messaging.Internal.InternalMessage internalMessage)
        {
            base.DeliverEvent(_source, new OnInternalMessageArrivalWeakEventArgs(internalMessage));
        }

        public static void AddListener(object source, IWeakEventListener listener)
        {            
            CurrentManager.ProtectedAddListener(source, listener);
        }

        public static void RemoveListener(object source, IWeakEventListener listener)
        {
            CurrentManager.ProtectedRemoveListener(source, listener);
        }

        private static OnInternalMessageArrivalManager CurrentManager
        {
            get
            {
                Type managerType = typeof(OnInternalMessageArrivalManager);
                OnInternalMessageArrivalManager currentManager = (OnInternalMessageArrivalManager)WeakEventManager.GetCurrentManager(managerType);
                if (currentManager == null)
                {
                    currentManager = new OnInternalMessageArrivalManager();
                    WeakEventManager.SetCurrentManager(managerType, currentManager);
                }
                return currentManager;
            }
        }
    }
}
